package com.woniuxy.util;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

public class ObjectRedisTemplate extends RedisTemplate<String ,Object> {
    public ObjectRedisTemplate(RedisConnectionFactory rcf){
        setConnectionFactory(rcf);
        setKeySerializer(RedisSerializer.string());
        setValueSerializer(RedisSerializer.json());
        setHashKeySerializer(RedisSerializer.string());
        setHashValueSerializer(RedisSerializer.string());
        afterPropertiesSet();
    }

    public <T> T get(String key,Class<T> type){
        return (T)opsForValue().get(key);
    }
//    public <T> List<T> getIndexList(String key,Integer minNum,Integer maxNum,Class<T> t){
//        List<Object> range = opsForList().range(key, minNum, maxNum);
//        List<T> needList= new ArrayList<T>();
//
//       for (Object o : range) {
//           System.out.println(o);
//            needList.add((T) o);
//           System.out.println((T)o);
//        }
//        System.out.println("方法调用"+needList);
//       return needList;
//    }


//    public <T> List<T> getZSetList(String key,Double minScore,Double maxScore,Class<T> t){
//        Set<Object> objects = opsForZSet().rangeByScore(key , minScore, maxScore);
//        List<Object> range = opsForList().range(key, minNum, maxNum);
//        List<T> needList= new ArrayList<T>();
//        for (Object o : range) {
//            needList.add((T) o);
//        }
//        return needList;
//    }
    public void addHashObject(String key,Object obj){
        Class<?> objClass = obj.getClass();
        Field[] fields = objClass.getDeclaredFields();
        Map<String, String> map = new HashMap<>();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object objvalue = field.get(obj);
                map.put(field.getName(),objvalue.toString());
                field.setAccessible(false);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        opsForHash().putAll(key,map);
    }

}
